/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */


#import "RecoverView.h"

#import "RecoverSyncMethodsView.h"

#import "CoreGraphics/CoreGraphics.h"

#import "spds/constants.h"


@implementation RecoverView

- (id) init {
    self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"Recover",@"Recover");
		menuList = [[NSMutableArray alloc] init];
        
        [self setRecoverDirection:@"recover-from-server"];
	}
	return self;
}    

- (void) dealloc {
    // TODO: destruct
    
    [super dealloc];
}

- (void) loadView{
    
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
	
	self.view.autoresizesSubviews = YES;

    small_font = [UIFont systemFontOfSize:15];
    

    SyncMethodsView* syncmethodsview = [[RecoverSyncMethodsView alloc] init];
    [syncmethodsview setSyncMode:@"recover-from-server"];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Sync Methods", @""), @"title",
                         syncmethodsview, @"viewController",
                         nil]];
	[syncmethodsview release];
    
    recoverTable = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    recoverTable.delegate = self;
    recoverTable.dataSource = self;
	//recoverTable.rowHeight = 40;
    [recoverTable setAutoresizesSubviews:YES];
    [recoverTable setAutoresizingMask:UIViewAutoresizingFlexibleHeight + UIViewAutoresizingFlexibleBottomMargin];
    
    [self.view addSubview:recoverTable]; 
    
    directionCell        =   [[UITableViewCell alloc]init];
    contactSyncCell      =   [[UITableViewCell alloc]init];


    descriptionCell      = [[UITableViewCell alloc] init];
    descriptionCell.selectionStyle = UITableViewCellSelectionStyleNone; 

    UITextView * description= [[UITextView alloc] initWithFrame: CGRectMake(20, 10, descriptionCell.contentView.bounds.size.width-40, 100)];
    description.text = NSLocalizedString(@"Recover Directions", @"Recover data...");
    [description setEditable:NO];
    [description setFont:small_font];
    [description setScrollEnabled:NO];
    [description setAutoresizesSubviews:YES];
    
    [descriptionCell addSubview:description];


    [directionCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [self setDirectionText];
    
    [[contactSyncCell textLabel] setText:NSLocalizedString(@"Contacts", @"Contacts...")];
    
    contactSync          =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [contactSync addTarget:self action:@selector(contactSyncAction:) forControlEvents:UIControlEventValueChanged];
    [contactSync setOn:YES animated:NO];

    [contactSyncCell addSubview:contactSync];
        
        
    recoverButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Begin",@"Begin...")
                                                  style:UIBarButtonItemStylePlain
                                                 target:self
                                                 action:@selector(recoverAction:)];

    self.navigationItem.rightBarButtonItem = recoverButton;
    [recoverButton setEnabled:YES];
    
    
    
    [recoverTable reloadData];
}

- (void) reload
{
}

- (void) viewDidAppear:(BOOL)animated{
    [self contactSyncAction:nil];
}

- (void) contactSyncAction: (id)sender
{
    if ([contactSync isOn])
    {
        [recoverButton setEnabled:YES];
    }
    else
    {
        [recoverButton setEnabled:NO];
    }
}

- (void) recoverAction: (id)sender
{
    if ([contactSync isOn])
    {
        clickedRecover = true;

        [[self navigationController] popViewControllerAnimated:YES];
    }
    else
    {
        clickedRecover = false;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return 110;
        default:
            return 40;
        break;
    }
    recoverTable.rowHeight;
}

- (UITableViewCell *)tableView:(UITableView *)contactsTable cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    return descriptionCell;
                default:
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    return directionCell;
                default:
                    break;
            }
            break;
        case 2:
            switch (indexPath.row) {
                case 0:
                    return contactSyncCell;
                default:
                    break;
            }
            break;
        default:

            break;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)contactsTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIViewController *targetViewController;
	switch (indexPath.section) {
        case 0:
            // Cannot select description
            [recoverTable deselectRowAtIndexPath:indexPath animated:YES];
            return;
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                    [((SyncMethodsView*)targetViewController) setSyncMode:direction];
                    [[self navigationController] pushViewController:targetViewController animated:YES];
                    
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }

}

- (NSInteger)tableView:(UITableView *)contactsTable numberOfRowsInSection:(NSInteger)section {
        switch (section) {
            case 0:
                return 1;
            case 1:
                return 1;
            case 2:
                // Number of categories
                return 1;
            default:
                break;
        }
    return 0;//should never happen
}



- (void)viewWillAppear:(BOOL)animated
{
    clickedRecover = false;
	UIViewController *targetViewController;
	NSString * mode;

	// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
	NSIndexPath *indexPath = [recoverTable indexPathForSelectedRow];
    if(!indexPath)
        return;
        
    switch (indexPath.section) {
        case 1:
            switch (indexPath.row) {
                case 0:
                    targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                    mode = [((SyncMethodsView*)targetViewController) getSyncMode];
                    [self setRecoverDirection:mode];
                    [mode release];
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
	[recoverTable deselectRowAtIndexPath:indexPath animated:NO];
    
    [self setDirectionText];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)contactsTable {
    return 3;
}


- (void) setDirectionText
{
    if ([direction isEqualToString:@"recover-from-server"])
    {
        [[directionCell textLabel] setText:[NSString stringWithFormat:@"%@ - %@", NSLocalizedString(@"Direction",@"Direction..."), @"From Server"]];
    }
    else
    {
        [[directionCell textLabel] setText:[NSString stringWithFormat:@"%@ - %@", NSLocalizedString(@"Direction",@"Direction..."), @"To Server"]];
    }
}


- (void) setRecoverDirection: (NSString*)dir
{
    if (dir == direction)
    {
        return;
    }
    
    if (direction)
    {
        [direction release];
    }
    
    direction = [dir copy];
}

- (NSString*) getRecoverDirection
{
    if (!direction)
        return nil;
    return [direction copy];
}

- (bool) didClickRecover
{
    return clickedRecover;
}
@end
